package cheme.ProcessEditor.DirectEdit;

import org.eclipse.draw2d.FigureUtilities;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.tools.CellEditorLocator;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.swt.widgets.List;

public class SelectionCellEditorLocator implements CellEditorLocator
{

	private Label label;

	/**
	 * Creates a new CellEditorLocator for the given Label
	 * 
	 * @param label
	 *            the Label
	 */
	public SelectionCellEditorLocator(Label label)
	{
		setLabel(label);
	}

	/**
	 * expands the size of the control by 1 pixel in each direction
	 */
	public void relocate(CellEditor celleditor)
	{
		List list = (List)celleditor.getControl();

		/*
		 * Note: This SWT function gives me inaccurate sizes, so the workaround used here is to
		 * employ FigureUtilities.getTextExtents(...) and calc the sizes locally.
		 */
		//Point pref = list.computeSize(SWT.DEFAULT, SWT.DEFAULT);

		Dimension currentDim;
		Dimension finalDim = new Dimension();
		
		for(int i = 0; i < list.getItemCount(); i++)
		{
			currentDim = FigureUtilities.getTextExtents(list.getItem(i), list.getFont());
			
			finalDim.width = Math.max(currentDim.width, finalDim.width);
			finalDim.height += currentDim.height;
		}
		
		finalDim.expand(4, 2);
		
		Rectangle rect = label.getBounds();
		label.translateToAbsolute(rect);
		
		list.setBounds(rect.x, rect.bottom() + 1, finalDim.width, finalDim.height);
	}

	/**
	 * Returns the Label figure.
	 * 
	 * @return the Label
	 */
	protected Label getLabel()
	{
		return label;
	}

	/**
	 * Sets the label.
	 * 
	 * @param label
	 *            The label to set
	 */
	protected void setLabel(Label label)
	{
		this.label = label;
	}

}